<?php

defined('CITY_BAO') or exit('Access Denied');
require CB_CORE . 'modules/' . $config_module['module'] . '/common.inc.php';
$action = $request->getActionName();
if ($action == 'upload') {
    define('NEED_LOGIN', true);
    if ($request->isPost()) {
        cb_init_uploader();
        $uploader->upload_form_field = 'file';
        $uploader->out_file_dir = CB_ROOT . get_avatar_path('origin');
        $uploader->process();
        $msg = '';
        if ($uploader->error_no) {
            switch ($uploader->error_no) {
                case 1:
                    $msg = "没有文件被上传";
                    break;
                case 2:
                case 5:
                    $msg = "该类型文件不允许被上传";
                    break;
                case 3:
                    $msg = "文件大小超出限制";
                    break;
                case 4:
                    $msg = "本地文件系统读写权限出错";
                    break;
                default:
                    $msg = "{$uploader->error_no}:发生未知错误，上传失败";
                    break;
            }
        } else {
            $image_handler = cb_init_image_handler();
            $image_handler->setMaskType(0);
            $image_handler->setSrcImg($uploader->saved_upload_name);
            $tmp_file = CB_DATA . 'temp/tmp_' . $uploader->parsed_file_name;
            $image_handler->setDstImg($tmp_file);
            $image_handler->createImg(380, 380);
            $msg = 'ok:' . str_replace(CB_ROOT, "", $tmp_file);
        }
        echo '<script type="text/javascript">window.parent.uploadresult("' . $msg . '");</script>';
        exit();
    }

    $tpl->assign('title', "上传头像");
    $tpl->display('member/avatar.tpl');
} elseif ($action == 'uploadsave') {
    define('NEED_LOGIN', true);
    $x = $request->getParam('x', 0);
    $y = $request->getParam('y', 0);
    $w = $request->getParam('w', 180);
    $h = $request->getParam('h', 180);
    $tmp_file = trim($request->getParam('s'));
    $tmp_file = substr($tmp_file, 0, (strpos($tmp_file, '?')));
    $tmp_file = CB_ROOT . substr($tmp_file, strlen(INSTALL_PATH));
    if (!file_exists($tmp_file)) {
        show_message('太神奇了，上传的图片找不到了，您的头像生成失败！', '-1');
    }
    $image_handler = cb_init_image_handler();
    $image_handler->setSrcImg($tmp_file);
    $thumbs = array('big' => array(180, 180), 'middle' => array(50, 50), 'small' => array(30, 30));
    $image_handler->setMaskType(0);
    foreach ($thumbs as $size => $num) {
        $avatar_name = get_avatar_name($user->userid, $size);
        $avatar = get_avatar_path($size, $user->userid) . $avatar_name;
        $avatar_filename = CB_ROOT . $avatar;
        $image_handler->setDstImg($avatar_filename);
        $image_handler->setCutType(2);
        $image_handler->setSrcCutPosition($x, $y);
        $image_handler->setSrcCut($w, $h);
        $image_handler->createImg($num[0], $num[1]);
        if ($error = $image_handler->getErrors()) {
            show_message('对不起，您的头像生成失败！可能的原因：' . $error[0], '-1');
        }
    }
    unlink($tmp_file);
    echo 'OK';
} else {
    $userid = abs(intval($request->getParam('userid', $user->userid)));
    $size = strtolower($request->getParam('size', 'middle'));
    $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
    $random = $request->getParam('random');
    $avatar_name = get_avatar_name($userid, $size);
    $avatar = get_avatar_path($size, $userid) . $avatar_name;
    $avatar_filename = CB_ROOT . $avatar;
    if (file_exists($avatar_filename)) {
        $random = $random ? rand(1000, 9999) : '';
        $avatar_url = empty($random) ? INSTALL_PATH . $avatar : INSTALL_PATH . $avatar . '?random=' . $random;
    } else {
        $avatar_url = IMG_DIR . 'noavatar_' . $size . '.gif';
    }

    if (empty($random)) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Last-Modified:" . date('r'));
        header("Expires: " . date('r', time() + 86400));
    }
    header('Location: ' . $avatar_url);
    exit;
}

/**
 * 获取头像文件名称
 * @param $userid
 * @param $size
 */
function get_avatar_name($userid, $size) {
    return "avatar_" . $userid . "_" . $size . ".jpg";
}

/**
 * 获取头像相关于系统根目录的路径
 *
 * @param $userid
 * @param $size
 */
function get_avatar_path($size, $userid=0) {
    $userid = abs(intval($userid));
    return "data/avatar/" . $size . "/";
}